import { createRouter, createWebHashHistory } from 'vue-router'
import { tokenStore,loginStore } from '@/store/modules/user'
import { routesStore, routeStore,nowPageStore} from '@/store/modules/routesInfo'

const routes = [
    {
        path: '/home',
        name: 'home',
        meta: {
            title: '主页'
        },
        component: () => import('@/views/Home.vue'),
        children: [
            {
                path: '/homePage',
                name: 'homePage',
                meta: {
                    title: '工作台'
                },
                component: () => import('@/views/home/homePage.vue')
            },
            {
                path: '/homes',
                name: 'homes',
                meta: {
                    title: 'sss'
                },
                component: () => import('@/views/home/homePage.vue')
            },
        ]
    },
    {
        path: '/',
        name: 'login',
        meta: {
            title: '用户登录'
        },
        component: () => import('@/views/login/Login.vue')
    },
    {
        path: '/regist',
        name: 'regist',
        meta: {
            title: '用户注册'
        },
        component: () => import('@/views/login/Regist.vue')
    },
    
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})
export default router
//2.路由发生变化修改页面title
router.beforeEach((to, from, next) => {
    let arr = routes[0].children?.map((item) => {
        return Object.assign({}, { title: item.meta.title, path: item.path})
    })
    routesStore().setRoutes(arr as any)
    if (to.meta.title) {
        document.title = to.meta.title as string;
        nowPageStore().setNowPage(to.meta.title as string)
        if(!routeStore().globalRoute.some(item => item.title === document.title) && document.title!='用户登录' && document.title!='用户注册'){
            routeStore().pushRoute({title:document.title,path:to.path})
        }
    }
    const userStore = tokenStore();
    const loginStatus=loginStore();
    if( userStore.token ){
        if(loginStatus.isLogin){
            next();
        }else{
            next('/');
        }
    }else{
        if(to.name=='login'||to.name=='regist'){
            next();
        }else{
            next('/');
        }
    }
});